<template>
  <a-modal
    :maskClosable="false"
    title="操作"
    centered
    :width="800"
    v-model="visible"
    :confirmLoading="confirmLoading"
    @ok="handleSubmit"
  >
    <a-form :form="form">
      <a-form-item style="display: none">
        <a-input v-decorator="['userId']" />
      </a-form-item>
      <a-form-item :labelCol="labelCol" :wrapperCol="wrapperCol" label="账号">
        <a-input
          :disabled="isEdit"
          placeholder="请输入账号"
          v-decorator="['loginName', { rules: [{ required: true, message: '请输入账号' }] }]"
          class="width-35"
        />
        <span v-if="!isEdit" class="_pl-20" style="color:#f5222d;">初始密码为: 123456</span>
      </a-form-item>
      <a-form-item :labelCol="labelCol" :wrapperCol="wrapperCol" label="姓名">
        <a-input
          v-decorator="[
            'userName',
            {
              rules: [{ required: true, message: '请输入姓名' }]
            }
          ]"
          placeholder="请输入姓名"
        />
      </a-form-item>
      <a-form-item :labelCol="labelCol" :wrapperCol="wrapperCol" label="手机号">
        <a-input
          placeholder="请输入手机号"
          v-decorator="[
            'phonenumber',
            { rules: [{ required: true, message: '请输入手机号' }, { validator: validatePhone }] }
          ]"
        />
      </a-form-item>
      <a-form-item :labelCol="labelCol" :wrapperCol="wrapperCol" label="邮箱">
        <a-input placeholder="请输入邮箱" v-decorator="['email', { rules: [{ validator: validateEmail }] }]" />
      </a-form-item>
      <a-form-item :labelCol="labelCol" :wrapperCol="wrapperCol" style="height: 104px" label="头像">
        <UploadImg v-model="imageUrl" :width="100" :height="100" cropper />
      </a-form-item>
      <a-form-item
        :labelCol="labelCol"
        :wrapperCol="wrapperCol"
        label="会员专员"
        extra="服务专员只能查看/管理已分配给TA管理的会员。在配置为服务专员时，建议把角色权限的【会员管理】-【所有用户】权限关闭。"
      >
        <a-radio-group
          v-decorator="['managerType', { initialValue: 1, rules: [{ required: true, message: '请选择会员专员' }] }]"
        >
          <a-radio :value="1">管理员(所有会员)</a-radio>
          <a-radio :value="2">专员(分配的会员)</a-radio>
        </a-radio-group>
      </a-form-item>
      <a-form-item :labelCol="labelCol" :wrapperCol="wrapperCol" label="状态">
        <a-select
          :disabled="isMaster"
          v-decorator="['status', { initialValue: '0', rules: [{ required: true, message: '请选择状态' }] }]"
        >
          <a-select-option :value="'0'">正常</a-select-option>
          <a-select-option :value="'1'">禁用</a-select-option>
        </a-select>
      </a-form-item>
      <a-form-item :labelCol="labelCol" :wrapperCol="wrapperCol" label="拥有角色" hasFeedback>
        <a-select
          style="width: 100%"
          v-decorator="['roleIds', { rules: [{ required: true, message: '请选择角色' }] }]"
          :allowClear="true"
          :disabled="isMaster"
        >
          <a-select-option v-for="action in roleAll" :key="action.roleId">{{ action.roleName }}</a-select-option>
        </a-select>
      </a-form-item>
      <a-form-item :labelCol="labelCol" :wrapperCol="wrapperCol" label="描述">
        <a-textarea :rows="5" v-decorator="['remark']" />
      </a-form-item>
    </a-form>
  </a-modal>
</template>
<script>
import { getRole4AdminAll, saveUser } from '@/api/system/system'
import pick from 'lodash.pick'
import UploadImg from '@/components/UpFile/uploadImg'

export default {
  name: 'UserModal',
  props: {
    deptTree: {
      type: Array,
      required: true
    }
  },
  components: {
    UploadImg
  },
  data() {
    return {
      visible: false,
      labelCol: {
        xs: { span: 24 },
        sm: { span: 5 }
      },
      wrapperCol: {
        xs: { span: 24 },
        sm: { span: 16 }
      },
      confirmLoading: false,
      roleAll: [],
      mdl: {},
      deptCheck: true,
      isload: true,
      loading: false,
      imageUrl: '',
      isEdit: false,
      isMaster: false,
      form: this.$form.createForm(this),
      managerType: 1
    }
  },
  beforeCreate() {},
  created() {
    this.loadRoleAll()
  },
  methods: {
    add() {
      this.imageUrl = ''
      this.form.resetFields()
      this.edit({ userId: 0, deptId: '' })
      this.isEdit = false
    },
    edit(record) {
      this.imageUrl = ''
      this.mdl = Object.assign({}, record)
      if (record.userId !== 0) {
        this.isEdit = true
      }
      this.visible = true
      console.log(this.mdl)
      this.isMaster = this.mdl.userId === -2
      this.$nextTick(() => {
        if (this.mdl.avatar) {
          this.imageUrl = this.mdl.avatar
        }
        this.form.setFieldsValue(
          pick(
            this.mdl,
            'userId',
            'email',
            'phonenumber',
            'loginName',
            'userName',
            'status',
            'managerType',
            'roleIds',
            'remark',
            'deptId'
          )
        )
        // this.form.setFieldsValue({ ...record })
        const roleId = []
        if (this.mdl.roles && this.mdl.roles.length) {
          roleId.push(this.mdl.roles[0].roleId)
        }
        this.form.setFieldsValue({ roleIds: roleId })
      })
    },
    //   * 校验手机号码
    validatePhone(rule, value, callback) {
      if (!/^1[3456789]\d{9}$/.test(value) && value) {
        callback(new Error('手机号码有误，请重填'))
      } else {
        callback()
      }
    },
    //   * 校验邮箱
    validateEmail(rule, value, callback) {
      if (!/^[a-zA-Z0-9]+([-_.][a-zA-Z0-9]+)*@[a-zA-Z0-9]+([-_.][a-zA-Z0-9]+)*\.[a-z]{2,}$/.test(value) && value) {
        callback(new Error('邮箱格式有误，请重填'))
      } else {
        callback()
      }
    },
    onChange(value, label, extra) {
      if (extra.triggerNode.$children.length > 0) {
        this.$message.error('不能选择父节点' + `${label}`)
        this.deptCheck = false
      } else {
        this.deptCheck = true
      }
    },
    loadRoleAll() {
      getRole4AdminAll().then(res => {
        this.roleAll = res.rows
        console.log('roleALl', this.roleAll)
      })
    },
    handleSubmit(e) {
      e.preventDefault()
      if (!this.deptCheck) {
        this.$message.error('不能选择父节点')
        return
      }
      this.form.validateFields((err, values) => {
        if (!err) {
          console.log('Received values of form: ', values)
          var params = JSON.parse(JSON.stringify(values))
          params.avatar = this.imageUrl
          params.roleIds = params.roleIds.toString()
          params.roleIds = [params.roleIds]
          this.confirmLoading = true
          var type = {
            userType: 'ADMIN_USER'
          }
          saveUser(Object.assign(params, type))
            .then(res => {
              this.$message.success('保存成功')
              this.visible = false
              if (this.isEdit) {
                this.$emit('reload')
              } else {
                this.$emit('ok')
              }
            })
            .finally(() => {
              this.confirmLoading = false
            })
        }
      })
    }
  },
  watch: {
    /*
      'selectedRows': function (selectedRows) {
        this.needTotalList = this.needTotalList.map(item => {
          return {
            ...item,
            total: selectedRows.reduce( (sum, val) => {
              return sum + val[item.dataIndex]
            }, 0)
          }
        })
      }
      */
  }
}
</script>
<style scoped>
.avatar-uploader > .ant-upload {
  width: 128px;
  height: 128px;
}

.avatar-uploader > .ant-upload img {
  width: 86px;
  height: 86px;
}

.ant-upload-select-picture-card i {
  font-size: 32px;
  color: #999;
}

.ant-upload-select-picture-card .ant-upload-text {
  margin-top: 8px;
  color: #666;
}
</style>
